package com.hubu.web;

import com.hubu.mapper.administratorUserMapper;
import com.hubu.pojo.administratorUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        //1.接受用户数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //封装用户对象
        administratorUser administratorUser =new administratorUser();
        administratorUser.setUsername(username);
        administratorUser.setPassword(password);


        //2. 调用Mybatis完成查询
        // 2.1 获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);

        //2.2获取SqlSession对象
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //2.3 获取Mapper
        administratorUserMapper userMapper=sqlSession.getMapper(administratorUserMapper.class);
        //2.4调用方法
        administratorUser u = userMapper.selectByUsername(username);

        if(u==null)
        {
            //用户名不存在
            userMapper.add(administratorUser);
            //提交数据库
            sqlSession.commit();
            //释放资源
            sqlSession.close();

            writer.println("<script type='text/javascript'>");
            writer.println("alert('注册成功！');");
            writer.println("window.location='" + request.getContextPath() + "/login.html';");
            writer.println("</script>");
        }
        else {
            //用户名存在，给出提示信息
            writer.println("<script type='text/javascript'>");
            writer.println("alert('注册失败，该用户名已被使用！');");
            writer.println("window.location='" + request.getContextPath() + "/register.html';");
            writer.println("</script>");
        }

}

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    this.doGet(request,response);
    }
}
